﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoboBrowse.Api;
using BoboBrowse.Facets;
using BoboBrowse.Facets.impl;
using Lucene.Net.Analysis;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
using WebApp1.Models;
using NewsMine.DomainObjects;
using NewsDiscoveryEngine.Index;

namespace WebApp1.AdminSection
{
    public partial class kwplanner : System.Web.UI.Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {
            //Here trying to map keywords and its categories.

            if (SecurityCheckManager.IsAdminPortalEabled() == false)
            {
                Response.Write("You should be the admin....");
                return;
            }


            string searchText = "titlelink:account OR titlelink:automobile OR titlelink:bank OR titlelink:bse OR titlelink:business OR titlelink:businessarticleshow OR titlelink:businesskhaskhabar OR titlelink:businessnews OR titlelink:commercial OR titlelink:companies OR titlelink:corporates OR titlelink:crore OR titlelink:dollar OR titlelink:economy OR titlelink:finance OR titlelink:forex OR titlelink:goodreturns OR titlelink:industry OR titlelink:lakh OR titlelink:markets OR titlelink:money OR titlelink:profit OR titlelink:rangarajan OR titlelink:rbi OR titlelink:rs OR titlelink:rupee OR titlelink:sensex OR titlelink:share OR titlelink:stock OR titlelink:stocks OR titlelink:tax OR titlelink:करोड़ OR titlelink:पैसे OR titlelink:बाजारों OR titlelink:रिजर्व OR titlelink:रुपए OR titlelink:रुपया OR titlelink:रुपये OR titlelink:रूपया OR titlelink:रूपये OR titlelink:शेयर OR titlelink:सेंसेक्स";
            string fieldName = "titlelink";

            long feedId  = -1;

            if (string.IsNullOrEmpty(this.Request.QueryString.Get("feedid")) == false)
            {
                if (long.TryParse(this.Request.QueryString.Get("feedid"), out feedId) == false)
                    feedId = -1;
            }
         
            FacetReader facetReader = new FacetReader();


            if (!string.IsNullOrEmpty(txtFieldName.Text) )
            {
                feedId = Convert.ToInt64(txtFieldName.Text);
            }

            if (feedId <= 0)
            {
                Response.Write("please provide valid feed id");
                return;
            }


            var feed = NewsDiscoveryEngine.FeedIndexSearcher.Instance.GetFeedById(feedId);

            if (feed == null)
                return;

            string testinput = feed.Title + " " + feed.Link;

            Dictionary<string, List<categoryRank>> deepAnalysisDetails = null;

            var analysisStats = facetReader.GetAnalyticalStatsForString(testinput, out deepAnalysisDetails);

            Response.Write(testinput);
            Response.Write("<br/>");

            analysisStats = (from stat in analysisStats
                             orderby stat.GlobalPercent descending
                             select stat).ToList();

            if (analysisStats.Where(x => x.Name != "*").Count() == 0)
            {
                Response.Write("No category matched.");
                return;
            }

            double maxGP = analysisStats.Where(x => x.Name!="*").Max(x => x.GlobalPercent);
            double totalGP = analysisStats.Where(x => x.Name == "*").First().GlobalPercent;
            int totalNumberOfItems = analysisStats.Count - 1; // because we need to take out the item for global stuff "*".




            foreach (var item in analysisStats)
            {
                var overallP = item.GlobalPercent * 100 / totalGP;
                var ratioAgainstMaxP = item.GlobalPercent * 100 / maxGP;

                Response.Write(item.Name + " - " + item.GlobalPercent + "  -  " + overallP + " %" + "  -  " + ratioAgainstMaxP + " %");

                if (   item.GlobalPercent >= 100 || ( ratioAgainstMaxP > 25 && overallP > 15) )
                {
                    Response.Write("   -   OK");
                }
                else
                {
                    Response.Write("   -   NOT OK");
                }

                Response.Write("<br/>");
            }

            Response.Write("<hr/>");
            Response.Write("<b>Details</b>");
            Response.Write("<br/>");

            foreach (var item in deepAnalysisDetails)
            {
                Response.Write("<p>");
                Response.Write(item.Key + "-");
                foreach (var k in item.Value)
                {
                    Response.Write(k.Name + " (" + k.GlobalPercent.ToString() + "%),");
                }
                Response.Write("</p>");
            }

           

            Response.Write("<hr/>");


           

            return;


            Dictionary<string, List<categoryRank>> results = facetReader.GetKeyWordDensityCloudForAllCategories();

            NewsMine.Utilities.FileExetensions.SerializeObjectToFileUsingProtoBuff("C:\\keyworkStats.dat", results);

           // results = (Dictionary<string, List<categoryRank>>)NewsMine.Utilities.FileExetensions.DeserializeFromFile<Dictionary<string, List<categoryRank>>>("C:\\keyworkStats.dat");


            Response.Write("Total number of documents :" + results.Count.ToString() + "<br/>");

            int runningCounter = 0;

            foreach (var item in results)
            {
                if (runningCounter++ >= 500)
                    break;
                Response.Write("<p>");
                Response.Write(item.Key + "-");
                foreach (var k in item.Value)
                {
                    Response.Write(k.Name + " (" + k.GlobalPercent.ToString() + "%),");
                }
                Response.Write("</p>");
            }

            //testing purpose only.

            return;


            var densityInfoList = facetReader.GetKeyWordDensityCloud(searchText, fieldName,"language:telugu");

            

       

            densityInfoList = (from item in densityInfoList
                               orderby 
                               item.TokenUniversalPercentage descending, 
                               item.TokenUniversalCount descending, item.ContextualTokenPercentage descending,
                               item.ContextualTokenCount descending, item.TokenCountPercentage descending,
                               (item.TokenCountPercentage - 5) * item.ContextualTokenPercentage descending
                               select item).ToList();


            Response.Write("<table>");
            Response.Write("<tr><th></th><th>Token Name</th><th></th><th>Count</th><th>Global Count</th><th>Universal Count</th><th> Relative %</th><th>Global %</th><th>Universal %</th><th>Score</th> </tr>");

            int count = 0;

            

            //alreadySelectedClassifiedKeywordsAlongWithStopWords.AddRange(NewsMine.DataManagers.KeyWordManager.GetAllKeywordsByCategory(stopWordCategory));

            //alreadySelectedClassifiedKeywordsAlongWithStopWords = alreadySelectedClassifiedKeywordsAlongWithStopWords.Distinct().ToList();



            int maxRecsPerpage = 5000;

            foreach (var item in densityInfoList)
            {
                if (count >= maxRecsPerpage)
                    break;

                if (count % 2 ==0)
                {
                    Response.Write("<tr style='background-color:#eee;'>");
                }
                else
                {
                    Response.Write("<tr>");
                }
               

                Response.Write("<td>");
                Response.Write((++count).ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.TokenName);
                Response.Write("</td>");


             

                Response.Write("<td>");
                Response.Write(item.TokenCount.ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.ContextualTokenCount.ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.TokenUniversalCount.ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.TokenCountPercentage.ToString());
                Response.Write(" %</td>");
                Response.Write("<td>");
                Response.Write(item.ContextualTokenPercentage.ToString());
                Response.Write(" %</td>");

                Response.Write("<td>");
                Response.Write(item.TokenUniversalPercentage.ToString());
                Response.Write(" %</td>");

                   Response.Write("<td>");
                   Response.Write((item.TokenUniversalPercentage * item.TokenCountPercentage).ToString());
                Response.Write(" points</td>");
              
                

            

                Response.Write("</tr>");

            }
            Response.Write("</table>");



         


        }


    }
}